import flask
import json
import time
import math
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
pool = ThreadPoolExecutor()

app = flask.Flask(__name__)

def is_prime(n):
    if n < 2:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False
    sqrt_n = int(math.floor(math.sqrt(n)))
    for i in range(3, sqrt_n + 1, 2):
        if n % i == 0:
            return False
    return True

def read_file():
    time.sleep(0.1)
    return 'file result'

def read_db():
    time.sleep(0.2)
    return 'db result'

def read_api():
    time.sleep(0.3)
    return 'api result'

@app.route('/is_prime/<numbers>')
def api_is_prime(numbers):
    number_list = list(map(int, numbers.split(",")))
    results = pool2.map(is_prime, number_list)
    return json.dumps(dict(zip(number_list, results)))

@app.route('/')
def index():
    result_file = pool.submit(read_file)
    result_db = pool.submit(read_db)
    result_api = pool.submit(read_api)

    return json.dumps({
        'result_file': result_file.result(),
        'result_db': result_db.result(),
        'result_api': result_api.result()
    })

if __name__ == '__main__':
    pool2 = ProcessPoolExecutor()
    app.run()